/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package edu.upf.grupE.impl;

import edu.upf.grupE.Controller.PictureController;
import edu.upf.grupE.Entities.Picture;
import edu.upf.grupE.Listener;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Packet;

/**
 *
 * @author xday666
 */
public class DownloadPictureListener implements Listener {

    private IM im;

    /**
     *
     * @param instancem
     */
    public DownloadPictureListener(final IM instancem) {
        im = instancem;
    }

    /**
     * we only work with the packets that are Messages. then we create a new Message
     * that will be the response to the search profile Message.
     * To be sure that the information that arrives to this listener is correct, we
     * print it into the Text Box.
     * Later we send back to the origin a Message containing the same object received.
     * @param packet
     */
    public final void processPacket(final Packet packet) {
        if (packet instanceof Message) {


            Message msg = (Message) packet;


            String downloadPicId = msg.getBody();

            Picture temp = PictureController.getById(Long.parseLong(downloadPicId));

            System.out.println(msg.getFrom() + " nos pide la foto " + downloadPicId);

            Message searchResult = new Message();
            searchResult.setTo(msg.getFrom());

            String path = temp.getFileDescriptor().getPath();


            File file = new File(path);

            byte[] bytes=null;
            try {
                bytes = getBytesFromFile(file);
            } catch (IOException ex) {
                Logger.getLogger(DownloadPictureListener.class.getName()).log(Level.SEVERE, null, ex);
            }

            searchResult.setProperty("DownloadResultPic", temp);
            searchResult.setProperty("image", bytes);
            searchResult.setPacketID(Config.PACKETPICRESULT);
            System.out.println("Enviandola");
            im.send(searchResult);
            System.out.println("Enviada!");


        }
    }

    public static byte[] getBytesFromFile(File file) throws IOException {
        InputStream is = new FileInputStream(file);

        // Get the size of the file
        long length = file.length();

        // You cannot create an array using a long type.
        // It needs to be an int type.
        // Before converting to an int type, check
        // to ensure that file is not larger than Integer.MAX_VALUE.
        if (length > Integer.MAX_VALUE) {
            // File is too large
        }

        // Create the byte array to hold the data
        byte[] bytes = new byte[(int)length];

        // Read in the bytes
        int offset = 0;
        int numRead = 0;
        while (offset < bytes.length
               && (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) {
            offset += numRead;
        }

        // Ensure all the bytes have been read in
        if (offset < bytes.length) {
            throw new IOException("Could not completely read file "+file.getName());
        }

        // Close the input stream and return bytes
        is.close();
        return bytes;
    }
}
